import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner;

/**
 * @author jcl_hqu
 * @date 2021/3/17 21:51
 */


public class Consumer {

    /**   消费者消费
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
//

        /* 共享文件虚拟共享内存*/
        RandomAccessFile raf = new RandomAccessFile("d:/shareMemory.mm", "rw");
        FileChannel fc = raf.getChannel();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 6); // 映射

        // 记录运行时间
        long start = 0;
        long end;

        int data; //  库存
        int count = 0; //记录消费次数


        while (count<100) {
            Thread.sleep(10);  //休眠10ms
                            /*进入区*/
            mbb.put(4,(byte) 1); mbb.put(5,(byte) 1);
            while (mbb.get(3) == (byte) 1 && mbb.get(5)==(byte) 1) System.out.println("消费者等待");

                                    /*  临界区*/
            if (count % 100 == 0) {
                start = System.currentTimeMillis(); //获取开始时间
            }

            mbb.put(4, (byte) 1); //消费者正在使用
            data  = mbb.get(0) * 100 + mbb.get(1) * 10 + mbb.get(2);  //获取库存数据

            // 库存大于0生产者才消费
            if (data > 0) {
                count++;
                data -= 1;

                        /*转换整形->字符串 */
                String buffer = String.valueOf(data) ;
                int length = buffer.length();
                if (length < 3) {
                    for (int i = 0; i < 3 - length; i++) {
                        buffer = "0" + buffer;
                    }
                }
                System.out.println("消费者消费," + "当前库存" + data  + "(" + count);

                // 写回数据
                mbb.put(0, (byte) (buffer.charAt(0) - '0'));
                mbb.put(1, (byte) (buffer.charAt(1) - '0'));
                mbb.put(2, (byte) (buffer.charAt(2) - '0'));
            }
            mbb.put(4, (byte) 0);
                            /*退出临界区*/

            //   输出打印时间
            if (count!=0&&count % 100 == 0) {
                end = System.currentTimeMillis();
                System.out.println("消费者花费时间:"+(end-start));
            }
        }
    }
}